<?php
/**
 * @author : shiminyan
 * @date: 2020/6/3 21:07
 */

namespace app\adminapi\controller;


use app\adminapi\model\Menu;
use app\adminapi\model\User;
use app\util\ReturnCode;
use app\util\Tools;


class Login extends Base
{
    /**
     * 登录方法
     * @return array
     */
    public function index(){

        $username =$this->request->param('username');
        $password = $this->request->param('password');
        if (!$username){
            return $this->buildFailed(ReturnCode::LOGIN_ERROR,'缺少用户名！');
        }
        if (!$password){
            return $this->buildFailed(ReturnCode::LOGIN_ERROR,'缺少密码！');
        }else{
            $password = Tools::userMd5($password);
        }
        $userInfo = User::where(['username'=>$username,'password'=>$password])->find();


        if (!empty($userInfo)){
            if ($userInfo['status']){
                //更新用户数据
                $userInfo->update_time=time();
                $userInfo->save();
            }else{
                return $this->buildFailed(ReturnCode::LOGIN_ERROR,'用户已被封禁，请联系管理员');
            }
        }else{
            return $this->buildFailed(ReturnCode::LOGIN_ERROR,'用户名密码不正确');
        }
        $apiAuth = md5(uniqid().time());
        cache('Login:'.$apiAuth,json_encode($userInfo),config('antadmin.ONLINE_TIME'));
        cache('Login:'.$userInfo['id'],$apiAuth,config('antadmin.ONLINE_TIME'));
        $userInfo['apiAuth']=$apiAuth;
        return $this->buildSuccess($userInfo,'登录成功');
    }

    /**
     * 用户登出
     */
    public function logout(){
        $apiAuth = request()->header('apiAuth');
        cache('Login:'.$apiAuth,null);
        cache('Login:'.$this->userInfo['id'],null);
        return $this->buildSuccess([],'登出成功');
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function getUserInfo(){
        return $this->buildSuccess($this->userInfo);
    }

    public function getAccess($uid){
        $isSupper = Tools::isAdministrator($uid);
        if ($isSupper){
            $access = Menu::where('show','1')->select();
            $access = Tools::buildArrFromObj($access);
            return array_values(array_filter(array_column($access,'url')));
        }else{
            return [];
        }
    }
}
